package com.ruoyix.weblog.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.ruoyix.common.helper.LoginHelper;
import com.ruoyix.common.utils.StringUtils;
import com.ruoyix.common.core.page.TableDataInfo;
import com.ruoyix.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyix.weblog.domain.BlogLabel;
import com.ruoyix.weblog.domain.BlogSort;
import com.ruoyix.weblog.mapper.BlogLabelMapper;
import com.ruoyix.weblog.mapper.BlogSortMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import com.ruoyix.weblog.domain.bo.BlogArticleBo;
import com.ruoyix.weblog.domain.vo.BlogArticleVo;
import com.ruoyix.weblog.domain.BlogArticle;
import com.ruoyix.weblog.mapper.BlogArticleMapper;
import com.ruoyix.weblog.service.IBlogArticleService;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 文章管理Service业务层处理
 *
 * @author ruoyi
 * @date 2024-05-27
 */
@RequiredArgsConstructor
@Service
public class BlogArticleServiceImpl implements IBlogArticleService {

    private final BlogArticleMapper baseMapper;

    private final BlogSortMapper sortMapper;

    private final BlogLabelMapper labelMapper;

    /**
     * 查询文章管理
     */
    @Override
    public BlogArticleVo queryById(Long id){
        BlogArticleVo blogArticleVo = baseMapper.selectVoById(id);
        blogArticleVo.setBlogLabel(labelMapper.selectById(blogArticleVo.getLabelId()));
        blogArticleVo.setBlogSort(sortMapper.selectById(blogArticleVo.getSortId()));
        return blogArticleVo;
    }

    /**
     * 查询文章管理列表
     */
    @Override
    public TableDataInfo<BlogArticleVo> queryPageList(BlogArticleBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<BlogArticle> lqw = buildQueryWrapper(bo);
        Page<BlogArticleVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        List<BlogArticleVo> records = result.getRecords();
        List<BlogArticleVo> articles = records.stream().map(article -> {
            BlogArticleVo articleVO = new BlogArticleVo();
            BeanUtils.copyProperties(article, articleVO);
            articleVO.setBlogSort(sortMapper.selectById(articleVO.getSortId()));
            articleVO.setBlogLabel(labelMapper.selectById(article.getLabelId()));
            return articleVO;
        }).collect(Collectors.toList());
        result.setRecords(articles);
        return TableDataInfo.build(result);
    }

    /**
     * 查询文章管理列表
     */
    @Override
    public List<BlogArticleVo> queryList(BlogArticleBo bo) {
        LambdaQueryWrapper<BlogArticle> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<BlogArticle> buildQueryWrapper(BlogArticleBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<BlogArticle> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getUserId() != null, BlogArticle::getUserId, bo.getUserId());
        lqw.eq(bo.getSortId() != null, BlogArticle::getSortId, bo.getSortId());
        lqw.eq(bo.getLabelId() != null, BlogArticle::getLabelId, bo.getLabelId());
        lqw.eq(StringUtils.isNotBlank(bo.getArticleCover()), BlogArticle::getArticleCover, bo.getArticleCover());
        lqw.eq(StringUtils.isNotBlank(bo.getImageUrl()), BlogArticle::getImageUrl, bo.getImageUrl());
        lqw.like(StringUtils.isNotBlank(bo.getArticleTitle()), BlogArticle::getArticleTitle, bo.getArticleTitle());
        lqw.eq(StringUtils.isNotBlank(bo.getArticleContent()), BlogArticle::getArticleContent, bo.getArticleContent());
        lqw.eq(bo.getViewCount() != null, BlogArticle::getViewCount, bo.getViewCount());
        lqw.eq(bo.getLikeCount() != null, BlogArticle::getLikeCount, bo.getLikeCount());
        lqw.eq(bo.getViewStatus() != null, BlogArticle::getViewStatus, bo.getViewStatus());
        lqw.eq(StringUtils.isNotBlank(bo.getPassword()), BlogArticle::getPassword, bo.getPassword());
        lqw.eq(StringUtils.isNotBlank(bo.getTips()), BlogArticle::getTips, bo.getTips());
        lqw.eq(bo.getRecommendStatus() != null, BlogArticle::getRecommendStatus, bo.getRecommendStatus());
        lqw.eq(bo.getCommentStatus() != null, BlogArticle::getCommentStatus, bo.getCommentStatus());
        lqw.eq(bo.getDelFlag() != null, BlogArticle::getDelFlag, bo.getDelFlag());
        return lqw;
    }

    /**
     * 新增文章管理
     */
    @Override
    public Boolean insertByBo(BlogArticleBo bo) {
        bo.setUserId(LoginHelper.getUserId());
        BlogArticle add = BeanUtil.toBean(bo, BlogArticle.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改文章管理
     */
    @Override
    public Boolean updateByBo(BlogArticleBo bo) {
        BlogArticle update = BeanUtil.toBean(bo, BlogArticle.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    @Override
    public Boolean updateLikeCount(Long id){
        BlogArticle blogArticle = baseMapper.selectById(id);
        blogArticle.setLikeCount(blogArticle.getLikeCount()+1);
        return baseMapper.updateById(blogArticle)>0;
    }

    @Override
    public Boolean updateViewCount(Long id){
        BlogArticle blogArticle = baseMapper.selectById(id);
        blogArticle.setViewCount(blogArticle.getViewCount()+1);
        return baseMapper.updateById(blogArticle)>0;
    }
    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(BlogArticle entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除文章管理
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public Map<String,String> getWebInfoMessage(){
        Map<String, String> webInfoMessage = baseMapper.selectWebInfoMessage();
        //Todo 配置到字典项
        webInfoMessage.put("webName","Stardust");
        webInfoMessage.put("avatar","http://10.18.85.21:9000/blog/2024/05/31/9c55b9623cb54790bafdccf83fcdcea0.png");
        return webInfoMessage;
    }


    @Override
    public List<Map<String, Object>> getArticlesByType(String title,int size) {
        List<BlogArticle> articleTypes = baseMapper.selectArticlesByTitle(title);
        List<Map<String, Object>> result = new ArrayList<>();

        for (BlogArticle type : articleTypes) {
            Map<String, Object> articlesByType = new HashMap<>();
            BlogSort sort = sortMapper.selectById(type.getSortId());
            List<BlogArticleVo> articlesList = baseMapper.selectArticlesBySortId(type.getSortId(), title,size);
            List<BlogArticleVo> articles = articlesList.stream().map(article -> {
                BlogArticleVo articleVO = new BlogArticleVo();
                BeanUtils.copyProperties(article, articleVO);
                return articleVO;
            }).collect(Collectors.toList());

            articles.forEach(item -> item.setBlogSort(sort));
            articles.forEach(item -> {
                BlogLabel label = labelMapper.selectById(item.getLabelId());
                item.setBlogLabel(label);
            });

            articlesByType.put("typeId", sort.getId());
            articlesByType.put("typeName", sort.getSortName());
            articlesByType.put("modelName", sort.getHomePageType());
            articlesByType.put("rows",sort.getSortRows());
            articlesByType.put("columns",sort.getSortColumns());
            articlesByType.put("articleName",sort.getArticlePageType());
            articlesByType.put("articles", articles);
            result.add(articlesByType);
        }

        return result;
    }
}
